﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using FrameworkLib.Utilities.CustomTypeDescriptor;

namespace FrameworkLib.Windows.Forms
{
    public class PropertyGridEx : PropertyGrid
    {
        private object m_selectedObject = null;
        private PropertyDecorator m_pm = null;

        public new object SelectedObject 
        {
            get { return base.SelectedObject; }
            set 
            {
                if (value != null)
                {
                    m_pm = new PropertyDecorator(value);
                }

                base.SelectedObject = value;

                TypeDescriptor.Refresh(this.SelectedObject);
            }
        }

        public PropertyGridEx()
        {
        }

        public void CustomSort(CustomSortOrder sortOrder)
        {
            this.PropertySort = PropertySort.NoSort;

            m_pm.DynamicCustomTypeDescriptor.PropertySortOrder = sortOrder;

            TypeDescriptor.Refresh(this.SelectedObject);
        }

        public void SetReadOnly(string propertyName, bool readOnly)
        {
            CustomPropertyDescriptor cpd = m_pm.DynamicCustomTypeDescriptor.GetProperty(propertyName);
            if (cpd != null)
            {
                cpd.SetIsReadOnly(readOnly);
                TypeDescriptor.Refresh(this.SelectedObject);
            }
        }

        public void SetVisible(string propertyName, bool visible)
        {
            CustomPropertyDescriptor cpd = m_pm.DynamicCustomTypeDescriptor.GetProperty(propertyName);
            if (cpd != null)
            {
                cpd.SetIsBrowsable(visible);
                TypeDescriptor.Refresh(this.SelectedObject);
            }
        }
    }
}
